package net.entelijan.cobean.worker;

import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

import net.entelijan.cobean.core.ICobean;
import net.entelijan.cobean.progress.DefaultProgressInitializer;
import net.miginfocom.swing.MigLayout;

public class RunDialog<R> extends JDialog implements IInternalTaskCompanion<R> {

	private static final long serialVersionUID = 1L;

	private JProgressBar progress = new JProgressBar();

	private int progressValue = 0;

	private JButton cancelButton = new JButton("Cancel");

	private Exception exception;

	private boolean finished;

	private ICobean<Integer> pcobean;

	public RunDialog(Window owner, String title) {
		super(owner);
		setModal(true);
		setTitle(title);

		DefaultProgressInitializer ini = new DefaultProgressInitializer();
		ini.setCoProgress(progress);

		pcobean = ini.initialize();

		Container cp = getContentPane();
		cp.setLayout(new MigLayout());
		cp.add(new JPanel(), "h 40, wrap");
		cp.add(progress, "w max, grow, wrap");
		cp.add(new JPanel(), "h max, grow, wrap");
		cp.add(createButtonsPanel(), "w max, grow");
		setSize(300, 150);
		setResizable(false);
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		setLocationRelativeTo(owner);
		cancelButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				finished = true;
			}

		});
	}

	private Component createButtonsPanel() {
		JPanel re = new JPanel();
		re.setLayout(new FlowLayout(FlowLayout.CENTER));
		re.add(cancelButton);
		return re;
	}

	@Override
	public void handleProgress() {
		if (finished) {
			throw new IllegalStateException("Was canceled");
		}
		pcobean.setValue(this.progressValue++);
	}

	public void finished(R returnValue) {
		dispose();
	}

	public void setException(Exception e) {
		this.exception = e;
	}

	public JProgressBar getProgress() {
		return progress;
	}

	public void setProgress(JProgressBar progress) {
		this.progress = progress;
	}

	public JButton getCancelButton() {
		return cancelButton;
	}

	public void setCancelButton(JButton cancelButton) {
		this.cancelButton = cancelButton;
	}

	public Exception getException() {
		return exception;
	}

	public void setFinished(boolean finished) {
		this.finished = finished;
	}

}
